package com.topc.participant.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.topc.base.exception.Asserts;
import com.topc.base.model.PageParams;
import com.topc.base.model.PageResult;
import com.topc.base.utils.PageUtils;
import com.topc.participant.model.dto.QueryRoleDto;
import com.topc.participant.model.po.MenuInfo;
import com.topc.participant.model.po.RoleInfo;
import com.topc.participant.mapper.RoleInfoMapper;
import com.topc.participant.service.IAdminInfoService;
import com.topc.participant.service.IRoleInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.topc.participant.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色信息 服务实现类
 * </p>
 *
 * @author Gogoing
 */
@Slf4j
@Service
public class RoleInfoServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements IRoleInfoService {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IAdminInfoService adminInfoService;

    @Override
    public PageResult<RoleInfo> searchRoleInfoByPage(PageParams pageParams, QueryRoleDto queryRoleDto) {
        Page page = this.getBaseMapper().searchRoleInfoByPage(pageParams.page(), queryRoleDto);
        return PageUtils.pageToResult(page);
    }

    @Override
    public void delRoleInfo(int type, Long roleId) {
        Boolean hasRole=true;
        if (type==1){
            hasRole = userInfoService.isHasRoleInUser(roleId);
        }else {
            hasRole =adminInfoService.isHasRoleInAdmin(roleId);
        }
        if (hasRole){
            Asserts.fail("还有角色没有转移");
        }
        LambdaUpdateWrapper<RoleInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RoleInfo::getId,roleId).eq(RoleInfo::getType,type);
        boolean remove = this.remove(updateWrapper);
        if (!remove) {
            Asserts.fail("删除失败");
        }
    }

    @Override
    public void addRoleInfo(RoleInfo roleInfo) {
        boolean save = this.save(roleInfo);
        if (!save) {
            Asserts.fail("添加失败");
        }
    }

    @Override
    public List<RoleInfo> getTypeRole(Integer type) {
        LambdaQueryWrapper<RoleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(RoleInfo::getId,RoleInfo::getRoleName).eq(RoleInfo::getType, type);
        List<RoleInfo> list = this.list(queryWrapper);
        return list;
    }
}
